﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using AjaxControlToolkit;
using System.Web.ModelBinding;
using OUSMS.AppLogic.BusinessLogicLayer;
using OUSMS.AppLogic.DataAccessLayer;
using OUSMS.Helpers;

namespace OUSMS
{
    public partial class CreateMotion : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                Motions motions = new Motions();
                MotionsBLL motionsBLL = new MotionsBLL();
                motions.Status = "";
                UsersBLL usersBLL = new UsersBLL();
                Users userEntity = usersBLL.GetUserByLoginName(User.Identity.Name);
                motions.ProposerID = userEntity.ID;
                motions = motionsBLL.CreateMotion(motions);
                motionIDHF.Value = motions.ID.ToString();

                StudyAreasBLL studyAreaBLL = new StudyAreasBLL();
                studyAreaDDL.DataSource = studyAreaBLL.GetALLStuyAreas().ToList();
                studyAreaDDL.DataBind();

                MotionFilesBLL motionFilesBLL = new MotionFilesBLL();
                filesGridView.DataSource = motionFilesBLL.GetMotionFilesByMotionID(Convert.ToInt64(motionIDHF.Value)).ToList();
                filesGridView.DataBind();

                DepartmentsBLL departmentsBLL = new DepartmentsBLL();
                IQueryable<Departments> departmentsList = departmentsBLL.GetAllDepartments();
                departmentChkboxList.DataSource = departmentsList.ToList();
                departmentChkboxList.DataBind();
            }
        }       

        protected void submitBtn_Click(object sender, EventArgs e)
        {
            try
            {
                UsersBLL usersBLL = new UsersBLL();
                Users userEntity = usersBLL.GetUserByLoginName(User.Identity.Name);
                MotionsBLL motionsBLL = new MotionsBLL();
                Motions motionEntity = motionsBLL.GetMotionsByID(Convert.ToInt64(motionIDHF.Value));
                motionEntity.Title = titleTxtBox.Text.Trim();
                motionEntity.Abstract = backgroundTxtBox.Text.Trim();
                motionEntity.Content = contentEditor.Text.Trim();
                motionEntity.Target = targetTxtBox.Text.Trim();
                motionEntity.Keywords = keywordsTxtBox.Text.Trim();
                motionEntity.ProposerID = userEntity.ID;
                motionEntity.Status = "待预审";
                motionEntity.StudyAreaID = Convert.ToInt32(studyAreaDDL.SelectedValue);
                motionEntity.Type = motionTypeDDL.SelectedValue;
                motionEntity.SumbitDateTime = DateTime.Now;
                MotionDepartmentsBLL motionDepartmentBLL = new MotionDepartmentsBLL();
                motionDepartmentBLL.ClearMotionDepartments(Convert.ToInt64(motionIDHF.Value));
                for (int i = 0; i < departmentChkboxList.Items.Count; i++)
                {
                    if (departmentChkboxList.Items[i].Selected)
                    {
                        MotionDepartments motionDepartments = new MotionDepartments();
                        motionDepartments.DepartmentID = Convert.ToInt32(departmentChkboxList.Items[i].Value);
                        motionDepartments.MotionID = Convert.ToInt64(motionIDHF.Value);
                        motionDepartmentBLL.AddMotionDepartment(motionDepartments);
                    }
                }
                motionsBLL.Save();
                Response.Redirect("MyMotionList.aspx");   
            }
            catch (Exception ex)
            {
                Logger.LogError(ex);
                errorMsgLbl.Text = string.Format("保存信息失败，失败原因：{0}，请报告管理员。", ex.Message);
            }
        }

        protected void ajaxFileUpload_OnUploadComplete(object sender, AjaxControlToolkit.AjaxFileUploadEventArgs e)
        {
            // Generate file path            
            string filePath = "/MotionPictures/" + Path.GetFileName(e.FileId) + Path.GetExtension(e.FileName);
            // Save uploaded file to the file system            
            var ajaxFileUpload = (AjaxFileUpload)sender;
            ajaxFileUpload.SaveAs(MapPath(filePath));
            // Update client with saved image path            
            e.PostedUrl = Page.ResolveUrl(filePath);
        }

        protected void saveBtn_Click(object sender, EventArgs e)
        {
            try
            {
                UsersBLL usersBLL = new UsersBLL();
                Users userEntity = usersBLL.GetUserByLoginName(User.Identity.Name);
                MotionsBLL motionsBLL = new MotionsBLL();
                Motions motionEntity = motionsBLL.GetMotionsByID(Convert.ToInt64(motionIDHF.Value));
                motionEntity.Title = titleTxtBox.Text.Trim();
                motionEntity.Abstract = backgroundTxtBox.Text.Trim();
                motionEntity.Content = contentEditor.Text.Trim();
                motionEntity.Target = targetTxtBox.Text.Trim();
                motionEntity.Keywords = keywordsTxtBox.Text.Trim();
                motionEntity.ProposerID = userEntity.ID;
                motionEntity.Status = "待提交";
                motionEntity.StudyAreaID = Convert.ToInt32(studyAreaDDL.SelectedValue);
                motionEntity.Type = motionTypeDDL.SelectedValue;
                MotionDepartmentsBLL motionDepartmentBLL = new MotionDepartmentsBLL();
                motionDepartmentBLL.ClearMotionDepartments(Convert.ToInt64(motionIDHF.Value));
                for (int i = 0; i < departmentChkboxList.Items.Count; i++)
                {
                    if (departmentChkboxList.Items[i].Selected)
                    {
                        MotionDepartments motionDepartments = new MotionDepartments();
                        motionDepartments.DepartmentID = Convert.ToInt32(departmentChkboxList.Items[i].Value);
                        motionDepartments.MotionID = Convert.ToInt64(motionIDHF.Value);                       
                        motionDepartmentBLL.AddMotionDepartment(motionDepartments);
                    }
                }
                motionsBLL.Save();
                Response.Redirect("MyMotionList.aspx");                
            }
            catch (Exception ex)
            {
                Logger.LogError(ex);
                errorMsgLbl.Text = string.Format("保存信息失败，失败原因：{0}，请报告管理员。",ex.Message);
                errorMsgLbl.Visible = true;
            }
        }

        protected void uploadButton_Click(object sender, EventArgs e)
        {
            MotionFiles motionFiles = new MotionFiles();
            MotionFilesBLL motionFilesBLL = new MotionFilesBLL();
            try
            {
                if (FileUpload.HasFile)
                {
                    motionFiles.FileName = FileUpload.FileName;
                    motionFiles.UploadDateTime = DateTime.Now;
                    motionFiles.MotionID = Convert.ToInt64(motionIDHF.Value);
                    motionFiles.Comment = FileUpload.FileName;
                    motionFiles.IsDeleted = false;

                    motionFilesBLL.CreateMotionFiles(motionFiles);

                    FileUpload.SaveAs(Request.PhysicalApplicationPath + string.Format("MotionFiles/{0}{1}", motionFiles.ID, Path.GetExtension(FileUpload.FileName)));

                    filesGridView.DataSource = motionFilesBLL.GetMotionFilesByMotionID(Convert.ToInt64(motionIDHF.Value)).ToList();
                    filesGridView.DataBind();
                }
            }
            catch (Exception ex)
            {
                motionFilesBLL.DeleteMotionFiles(motionFiles);
                Logger.LogError(ex);
            }
        }

        protected void filesGridView_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                Label indexLbl = e.Row.FindControl("indexLbl") as Label;
                indexLbl.Text = (e.Row.RowIndex + 1).ToString();

                MotionFiles motionFileEntity = e.Row.DataItem as MotionFiles;
                Label fileNameLbl = e.Row.FindControl("fileNameLbl") as Label;
                fileNameLbl.Text = motionFileEntity.FileName.Length > 25 ? motionFileEntity.FileName.Substring(0, 24) + "..." : motionFileEntity.FileName;
                fileNameLbl.ToolTip = motionFileEntity.FileName;
            }
        }

        protected void deleteLinkButton_Click(object sender, EventArgs e)
        {
            try
            {
                MotionFilesBLL motionFilesBLL = new MotionFilesBLL();
                LinkButton deleteLinkButton = sender as LinkButton;
                MotionFiles motionFile = motionFilesBLL.GetMotionFileByID(Convert.ToInt64(deleteLinkButton.CommandArgument));
                motionFilesBLL.DeleteMotionFiles(motionFile);
                filesGridView.DataSource = motionFilesBLL.GetMotionFilesByMotionID(Convert.ToInt64(motionIDHF.Value)).ToList();
                filesGridView.DataBind();
            }
            catch (Exception ex)
            {
                Logger.LogError(ex);
                errorMsgLbl.Text = string.Format("删除文件失败,失败原因:{0}", ex.Message);
                errorMsgLbl.Visible = true;
            }
        }    
    }
}